#include "systemsetting.h"
#include "ui_systemsetting.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QTextStream>
#include <QMenu>

SystemSetting::SystemSetting(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SystemSetting),
    m_logsModel(new QStandardItemModel(this)),
    m_dbManager(nullptr)
{
    ui->setupUi(this);

    setupModel();
    populateTypeComboBox();
    populateLevelComboBox();

    ui->startDateTimeEdit->setDateTime(QDateTime::currentDateTime().addDays(-7));
    ui->endDateTimeEdit->setDateTime(QDateTime::currentDateTime());

    setupConnections();
    loadLogs();
}

SystemSetting::~SystemSetting()
{
    delete ui;
    delete m_logsModel;
}

void SystemSetting::setDatabaseManager(DatabaseManager* manager) {
    m_dbManager = manager;
}

void SystemSetting::log(const QString &content,
                       const QString &logType,
                       const QString &logLevel,
                       int userId,
                       int deviceId)
{
    QString escapedContent = content;
    escapedContent.replace("'", "''");

    QString sql = QString("INSERT INTO system_logs (timestamp, log_type, log_level, content, user_id, device_id) "
                         "VALUES ('%1', '%2', '%3', '%4', %5, %6)")
                         .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"))
                         .arg(logType)
                         .arg(logLevel)
                         .arg(escapedContent)
                         .arg(userId == -1 ? "NULL" : QString::number(userId))
                         .arg(deviceId == -1 ? "NULL" : QString::number(deviceId));

    DatabaseManager::instance()->sendRequest(sql);
}

void SystemSetting::setupModel()
{
    m_logsModel->setHorizontalHeaderLabels(
        {"日志ID", "时间", "类型", "等级", "内容", "用户ID", "设备ID"});
    ui->logsTableView->setModel(m_logsModel);
    ui->logsTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    ui->logsTableView->setContextMenuPolicy(Qt::CustomContextMenu);
}

void SystemSetting::setupConnections()
{
    connect(ui->queryButton, &QPushButton::clicked, this, &SystemSetting::onQueryLogs);
    connect(ui->exportButton, &QPushButton::clicked, this, &SystemSetting::onExportLogs);
    connect(ui->logsTableView, &QTableView::customContextMenuRequested,
            this, &SystemSetting::showContextMenu);
}

void SystemSetting::populateTypeComboBox()
{
    ui->typeComboBox->clear();
    ui->typeComboBox->addItem("所有类型", "");
    ui->typeComboBox->addItem("系统日志", "system");
    ui->typeComboBox->addItem("操作日志", "operation");
    ui->typeComboBox->addItem("告警日志", "alarm");
    ui->typeComboBox->addItem("异常日志", "exception");
}

void SystemSetting::populateLevelComboBox()
{
    ui->levelComboBox->clear();
    ui->levelComboBox->addItem("所有等级", "");
    ui->levelComboBox->addItem("信息", "INFO");
    ui->levelComboBox->addItem("警告", "WARNING");
    ui->levelComboBox->addItem("错误", "ERROR");
    ui->levelComboBox->addItem("严重", "CRITICAL");
}

QString SystemSetting::buildQueryString() const
{
    QDateTime startTime = ui->startDateTimeEdit->dateTime();
    QDateTime endTime = ui->endDateTimeEdit->dateTime();
    QString logType = ui->typeComboBox->currentData().toString();
    QString logLevel = ui->levelComboBox->currentData().toString();

    QString queryStr = QString("SELECT log_id, timestamp, log_type, log_level, content, user_id, device_id "
                             "FROM system_logs WHERE timestamp BETWEEN '%1' AND '%2'")
                             .arg(startTime.toString("yyyy-MM-dd hh:mm:ss"))
                             .arg(endTime.toString("yyyy-MM-dd hh:mm:ss"));

    if(!logType.isEmpty()) {
        queryStr += QString(" AND log_type = '%1'").arg(logType);
    }
    if(!logLevel.isEmpty()) {
        queryStr += QString(" AND log_level = '%1'").arg(logLevel);
    }
    queryStr += " ORDER BY timestamp DESC LIMIT 1000";

    return queryStr;
}

void SystemSetting::loadLogs()
{
    m_logsModel->removeRows(0, m_logsModel->rowCount());

    QString queryStr = buildQueryString();
    QString response = m_dbManager->sendRequest(queryStr);

    if(response.startsWith("Error:")) {
        QMessageBox::critical(this, "错误", "查询日志失败: " + response.mid(6));
        return;
    }

    QStringList rows = response.split("\n", QString::SkipEmptyParts);
    foreach(const QString &row, rows) {
        QStringList columns = row.split("|", QString::SkipEmptyParts);
        if(columns.size() < 7) continue;

        QList<QStandardItem*> rowItems;
        rowItems << new QStandardItem(columns[0].trimmed())
                << new QStandardItem(columns[1].trimmed())
                << new QStandardItem(columns[2].trimmed())
                << new QStandardItem(columns[3].trimmed())
                << new QStandardItem(columns[4].trimmed())
                << new QStandardItem(columns[5].trimmed())
                << new QStandardItem(columns[6].trimmed());
        m_logsModel->appendRow(rowItems);
    }
}

void SystemSetting::onQueryLogs()
{
    loadLogs();
}

void SystemSetting::onExportLogs()
{
    QString fileName = QFileDialog::getSaveFileName(this, "导出日志", "", "CSV文件 (*.csv)");
    if(fileName.isEmpty()) return;

    QFile file(fileName);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&file);

        for(int col = 0; col < m_logsModel->columnCount(); ++col) {
            out << "\"" << m_logsModel->horizontalHeaderItem(col)->text() << "\"";
            if(col < m_logsModel->columnCount() - 1) out << ",";
        }
        out << "\n";

        for(int row = 0; row < m_logsModel->rowCount(); ++row) {
            for(int col = 0; col < m_logsModel->columnCount(); ++col) {
                out << "\"" << m_logsModel->item(row, col)->text() << "\"";
                if(col < m_logsModel->columnCount() - 1) out << ",";
            }
            out << "\n";
        }

        file.close();
        QMessageBox::information(this, "成功", "日志导出完成");
    } else {
        QMessageBox::warning(this, "错误", "无法创建文件");
    }
}

void SystemSetting::showContextMenu(const QPoint &pos)
{
    QMenu menu(this);
    QAction *deleteAction = menu.addAction("删除日志");

    QModelIndex index = ui->logsTableView->indexAt(pos);
    if(!index.isValid()) {
        deleteAction->setEnabled(false);
    }

    QAction *selectedAction = menu.exec(ui->logsTableView->viewport()->mapToGlobal(pos));
    if(selectedAction == deleteAction) {
        deleteSelectedLog();
    }
}

void SystemSetting::deleteSelectedLog()
{
    QModelIndexList selected = ui->logsTableView->selectionModel()->selectedRows();
    if(selected.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择要删除的日志");
        return;
    }

    int logId = m_logsModel->item(selected.first().row(), 0)->text().toInt();

    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认删除",
                                "确定要删除选中的日志吗？此操作不可撤销！",
                                QMessageBox::Yes | QMessageBox::No);

    if(reply == QMessageBox::Yes) {
        QString sql = QString("DELETE FROM system_logs WHERE log_id = %1").arg(logId);
        QString response = m_dbManager->sendRequest(sql);

        if(response.contains("successfully")) {
            loadLogs();
            QMessageBox::information(this, "成功", "日志已删除");
        } else {
            QMessageBox::critical(this, "错误", "删除失败: " + response);
        }
    }
}
